package com.accenture.automation.common;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**********************
 * 字符串工具类<br>bbz
************************/
public class StringUtil {

    /**
     * 根据指定的字节数截取字符串
     * 
     * @param srcStr
     *            源字符串
     * @param byteLength
     *            截取字节数
     * @return 截取后的字符串
     */
    public static String truncateString(String srcStr, int byteLength) {

        // 返回null
        if (srcStr == null) {
            return null;
        }

        // 返回空
        if (srcStr.trim().length() == 0) {
            return "";
        }

        // 返回异常
        if (byteLength < 0) {
            throw new IllegalArgumentException(
                    "Parameter byteLength must be great than 0");
        }

        // 将传入的字符串转成字符数组
        char[] strCharArray = srcStr.toCharArray();

        // 获取字符数组的长度，即字符串的字符数
        int strLength = strCharArray.length;

        // 设定已获取字节个数为0
        int getByteLength = 0;

        int i = 0;
        while (getByteLength < byteLength && i < strLength) {

            // 如果字符大于255则已获取字节数+2，否则+1
            getByteLength = (strCharArray[i++] > 0xFF) ? getByteLength + 2
                    : getByteLength + 1;

        }

        // 如果已获得字节数超过所要获取的自己长度则结束循环
        if (getByteLength > byteLength) {
            i--;
        }

        return new String(strCharArray, 0, i);
    }

    /**
     * 判断字符串是否为空或Null
     * 
     * @param srcStr
     *            源字符串
     * @return 为空或Null返回true，否则返回false
     */
    public static boolean isEmptyOrNull(String srcStr) {
        return (srcStr == null || srcStr.trim().length() == 0 || "null"
                .equalsIgnoreCase(srcStr.trim()));
    }

    /**
     * 校验源字符串是否为空，如果为空，则用目标代替字符串替换
     * 
     * @param srcStr
     *            源字符串
     * @param replaceStr
     *            代替字符串
     * @return 空字符串返回代替字符串，否则返回源字符串
     * @author demo@neusoft.com (2011-9-14 下午5:34:04)
     */
    public static String checkNilStr(String srcStr, String replaceStr) {
        String tmpStr = null;
        if (isEmptyOrNull(srcStr)) {
            if (isEmptyOrNull(replaceStr)) {
                tmpStr = "";
            } else {
                tmpStr = replaceStr;
            }
        } else {
            tmpStr = srcStr;
        }
        return tmpStr;
    }

    /**
     * 校验并返回带有特定结尾符的字符串
     * 
     * @param srcStr
     *            源字符串
     * @param postfix
     *            结尾符
     * @return 带有结尾符的字符串
     */
    public static String checkEndWith(String srcStr, String postfix) {

        if (isEmptyOrNull(srcStr)) {
            return "";
        }

        if (isEmptyOrNull(postfix)) {
            return srcStr;
        }

        if (srcStr.endsWith(postfix)) {
            return srcStr;
        } else {
            return srcStr + "" + postfix;
        }

    }

    /**
     * 
     * 
     * @param obj
     * @return String
     * @throws UnsupportedEncodingException
     */

    /**
     * 转码[GBK -> iso-8859-1] 不同的平台需要不同的转码
     * 
     * @param srcStr
     *            源字符串对象
     * @param controlEncoding
     *            编码格式
     * @return 转码后的字符串
     * @throws UnsupportedEncodingException
     *             不支持转码
     */
    public static String controlEncoding(String srcStr, String controlEncoding)
            throws UnsupportedEncodingException {
        if (srcStr == null) {
            return "";
        } else {
            return new String(srcStr.getBytes(controlEncoding),
                    "iso-8859-1");
        }
    }

    /**
     * 字节数组转字符串
     * 
     * @param bytes
     *            源字节数组
     * @return 转换的到的字符串
     */
    public static String bytes2String(byte[] bytes) {
        String result = "";
        for (Byte b : bytes) {
            result += (char) b.intValue();
        }
        return result;
    }

    /**
     * 字节数组转16进制串
     * 
     * @param in
     *            输入字节数组
     * @return 16进制字符串
     */
    public static String bytesToHex(byte[] in) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < in.length; n++) {
            stmp = (Integer.toHexString(in[n] & 0XFF));
            if (stmp.length() == 1) {
                hs = hs + "0" + stmp;
            } else {
                hs = hs + stmp;
            }
        }
        return hs.toLowerCase();
    }
    
    /**
     * 根据输入的字符串参数值，转换为boolean表达式
     * 
     * @param flag
     *            字符串，0或1
     * @return 输入参数为1时返回 true，否则返回false
     */
    public static boolean isTrue(String flag) {
        return "1".equals(flag);
    }

    /**
     * 16进制转字节数组
     * 
     * @param src
     *            16进制串
     * @return 字节数组
     */
    public static byte[] hexToBytes(String src) {
        int l = src.length() / 2;
        String str;
        byte[] ret = new byte[l];

        for (int i = 0; i < l; i++) {
            str = src.substring(i * 2, i * 2 + 2);
            ret[i] = (byte) (0xff & Integer.parseInt(str, 16));
        }
        return ret;
    }

    /**
     * 获得字符串中时间
     * 
     * @param string
     *            字符串
     * @param timeFormat
     *            时间格式
     * @param indexNo
     *            获得时间索引号
     * @return timeStr 字符串中时间
     */
    public static String getStringTime(String string, String timeFormat,
            int indexNo) {
        String timeStr = "";
        // 生成正则表达式
        String regexStr = timeFormat
                .replaceAll("yyyy", CommonConstants.YEAR_REGEX)
                .replaceAll("MM", CommonConstants.MONTH_REGEX)
                .replaceAll("dd", CommonConstants.DAY_REGEX)
                .replaceAll("HH", CommonConstants.HOUR_REGEX)
                .replaceAll("mm", CommonConstants.MINUTE_REGEX)
                .replaceAll("ss", CommonConstants.SECOND_REGEX);
        try {
            Pattern p = Pattern.compile(regexStr);
            Matcher m = p.matcher(string);
            List<String> timeList = new ArrayList<String>();
            while (m.find()) {
                timeList.add(m.group());
            }
            timeStr = timeList.get(indexNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return timeStr;
    }
    
    /**
     * 
     * Create date:2012-6-6
     * Method name:padRight
     * Description: 字符串右侧补齐
     * return:String
     */
	public static String padRight(String str, int len, String c) {
		if (null == str) {
			str = "";
		}
		while (str.length() < len) {
			str += c;
		}
		return str;
	}
	/**
	 * 
	 * Create date:2012-6-7
	 * Method name:padLeft
	 * Description: 字符串左侧补齐
	 * return:String
	 */
	public static String padLeft(String str, int len, String c) {
		if (null == str) {
			str = "";
		}
		while (str.length() < len) {
			str = c + str;
		}
		return str;
	}
	
	/**
	 * 
	 * Create date:2012-6-12
	 * Method name:delAfterStr
	 * Description: 从字符串末尾开始往前删除指定的字符，直到碰到第一个不为c的字符
	 * return:String
	 */
	public static String delAfterStr(String str, char c, int len) {
		for (int i = str.length() - 1; i >= len; i--) {
			char cc = str.charAt(i);
			if (c == cc) {
				str = str.substring(0, i);
			} else {
				break;
			}
		}
		return str;
	}
	
	
	 public static byte[] hexStringToBytes(String hexString)
	    {
	      if ((hexString == null) || (hexString.equals(""))) {
	        return null;
	      }
	      hexString = hexString.toUpperCase();
	      int length = hexString.length() / 2;
	      char[] hexChars = hexString.toCharArray();
	      byte[] d = new byte[length];
	      for (int i = 0; i < length; i++) {
	        int pos = i * 2;
	        d[i] = (byte)(charToByte(hexChars[pos]) << 4 | charToByte(hexChars[(pos + 1)]));
	      }
	      return d;
	    }
	    private static byte charToByte(char c)
	    {
	        return (byte)"0123456789ABCDEF".indexOf(c);
	    }
	    
	    
	    /** *//**
	     * 把字节数组转换成16进制字符串
	     * @param bArray
	     * @return
	     */
	    public static final String bytesToHexString(byte[] bArray) {
//	     StringBuffer sb = new StringBuffer(bArray.length);
//	     String sTemp;
//	     for (int i = 0; i < bArray.length; i++) {
//	      sTemp = Integer.toHexString(0xFF & bArray[i]);
//	      if (sTemp.length() < 2)
//	       sb.append(0);
//	      sb.append(sTemp.toUpperCase());
//	     }
//	     return sb.toString();
	    	
	    	 StringBuilder stringBuilder = new StringBuilder("");   
	    	     if (bArray == null || bArray.length <= 0) {   
	    	        return null;   
	    	     }   
	    	    for (int i = 0; i < bArray.length; i++) {   
	    	        int v = bArray[i] & 0xFF;   
	    	         String hv = Integer.toHexString(v);   
	    	        if (hv.length() < 2) {   
	    	            stringBuilder.append(0);   
	    	        }   
	    	         stringBuilder.append(hv);   
	    	     }   
	    	     return stringBuilder.toString();   
	    }
	    
	    public static String list2String(List<String> list, String splitStr) {
			String result = "";
			for (String str : list) {
				result = result + str + splitStr;
			}
			if (result.length() > 0) {
				result = result.substring(0, result.lastIndexOf(splitStr));
			}
			return result;
		}
	    
}
